package com.example.tangyee.fragment;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.tangyee.R;
import com.example.tangyee.activity.PredictActivity;
import com.example.tangyee.bean.Meal;
import com.example.tangyee.utils.ConstantsUtil;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MealFragmentForViewPager extends Fragment {

    private static final String TAG = "DietFragmentForVP";

    private static final String PARAM = "param";
    
    private int energy;

    public static MealFragmentForViewPager newInstance(int value) {
        MealFragmentForViewPager fragment = new MealFragmentForViewPager();
        Bundle args = new Bundle();
        args.putInt(PARAM, value);
        fragment.setArguments(args);
        return fragment;
    }

    private Unbinder mUnbinder;


    @BindView(R.id.loading_view)
    View loadingView;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private MealAdapter mAdapter;
    private StaggeredGridLayoutManager layoutManager;

    private GetMealSetsInJson asyncTask;


    private String[] x = new String[] { "碳水化合物", "蛋白质", "脂肪"};

    /*控制懒加载*/
    boolean mIsPrepare = false;		//视图还没准备好
    boolean mIsVisible= false;		//不可见
    boolean mIsFirstLoad = true;	//第一次加载

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        energy = bundle.getInt(PARAM);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIsPrepare = true;
        lazyLoad();
    }

    private void lazyLoad() {
        if (!mIsPrepare || !mIsVisible || !mIsFirstLoad) {
            return;
        }

        loadData();
        mIsFirstLoad = false;
    }

    private void loadData() {
        asyncTask = new GetMealSetsInJson();
        asyncTask.execute();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_diet_for_view_pager, container, false);
        mUnbinder = ButterKnife.bind(this,view);

        /*
         * 下拉刷新
         * */
        refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (asyncTask != null) {
                asyncTask.cancel(true);
            }
            loadingView.findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
            TextView textView = loadingView.findViewById(R.id.loading);
            textView.setText("努力加载中···");
            asyncTask = new GetMealSetsInJson();
            asyncTask.execute();
        });
        initView();

        return view;
    }

    private void initView() {
        mAdapter = new MealAdapter(new ArrayList<>());
        layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(layoutManager);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            mIsVisible = true;
            lazyLoad();
        } else {
            mIsVisible = false;
        }
    }

    //显示饼图
    public void showPieChart(PieChart pieChart, ArrayList<Float> y) {
        try {
            PieData pieData = setData(y.size(), y);
            setPieChart(pieChart, pieData);
        } catch (NullPointerException npe) {
            Log.e(TAG, "showPieChart: ", npe);
        }
    }
    //设置饼图的相关信息
    private void setPieChart(PieChart pieChart, PieData pieData) {
        if (pieChart == null || pieData == null) {
            return;
        }
        pieChart.setHighlightPerTapEnabled(false);
        pieChart.setHoleRadius(0f);
        pieChart.setTransparentCircleRadius(0f);
        Description description = new Description();
        description.setText("");
        description.setTextSize(15f);
        description.setPosition(400, 50);
        description.setTextColor(Color.parseColor("#ff9933"));
        pieChart.setDescription(description);
        pieChart.setDrawHoleEnabled(false);
        pieChart.setExtraOffsets(0, 0, 0, 0);
        pieChart.setDrawEntryLabels(false);
        pieChart.setEntryLabelTextSize(20f);
        pieChart.setRotationAngle(-90f);
        pieChart.setUsePercentValues(true);
        pieChart.setRotationEnabled(false);
        pieChart.setData(pieData);
//        pieChart.animateXY(500, 500);
        Legend legend = pieChart.getLegend();
        legend.setEnabled(true);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setFormSize(10);
        legend.setFormToTextSpace(10f);
        legend.setYEntrySpace(5f);
        legend.setYOffset(20f);
        legend.setTextSize(10f);
        legend.setTextColor(Color.parseColor("#ff9933"));
    }

    //添加数据到饼图中
    private PieData setData(int count, ArrayList<Float> y) {
        ArrayList<String> xVals = new ArrayList<>();
        ArrayList<PieEntry> yVals = new ArrayList<>();
        for (int xi = 0; xi < count; xi++) {
            yVals.add(new PieEntry(y.get(xi), x[xi]));
        }
        PieDataSet yDataSet = new PieDataSet(yVals, "");
        yDataSet.setSliceSpace(0);

        yDataSet.setValueLinePart1OffsetPercentage(80.f);
        yDataSet.setValueLinePart1Length(0.5f);
        yDataSet.setValueLinePart2Length(0.7f);
        yDataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(Color.rgb(52,152,219));
        colors.add(Color.rgb(46,204,113));
        colors.add(Color.rgb(241,196,15));
        yDataSet.setColors(colors);
        PieData pieData = new PieData(yDataSet);
        pieData.setDrawValues(true);
        pieData.setValueTextColor(Color.BLUE);
        pieData.setValueTextSize(15f);
        pieData.setValueFormatter(new PercentFormatter());
        pieData.setValueFormatter(new PercentFormatter());
        pieData.setValueTextColor(Color.BLACK);
        return pieData;
    }

    private class MealAdapter extends RecyclerView.Adapter<MealViewHolder> {

        private List<Meal> mMeals;

        MealAdapter(List<Meal> meals) {
            mMeals = meals;
        }

        public void setMeals(List<Meal> meals) {
            this.mMeals = meals;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public MealViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            return new MealViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_meal_layout,viewGroup,false));
        }

        @Override
        public void onBindViewHolder(@NonNull MealViewHolder mealViewHolder, int i) {
            Meal meal = mMeals.get(i);
            mealViewHolder.title.setText(meal.getMealName());
            mealViewHolder.ingredient.setText(meal.getElements());
            PieChart pieChart = mealViewHolder.mPieChart;
            ArrayList<Float> y = new ArrayList<>();
            y.add((float) meal.getCarbohydrate());
            y.add((float) meal.getProtein());
            y.add((float) meal.getFat());
            showPieChart(pieChart, y);
        }

        @Override
        public int getItemCount() {
            return mMeals.size();
        }
    }

    private class MealViewHolder extends RecyclerView.ViewHolder {

        TextView title;
        PieChart mPieChart;
        TextView ingredient;

        public MealViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            mPieChart = itemView.findViewById(R.id.pie_chart);
            ingredient = itemView.findViewById(R.id.ingredient);
        }
    }

    private class GetMealSetsInJson extends AsyncTask<Void, Void, List<Meal>> {


        @Override
        protected List<Meal> doInBackground(Void... voids) {
            if (isCancelled()) {
                return null;
            }

            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody requestBody = new FormBody.Builder()
                    .add("iState", "1")
                    .add("iMin", "" + (energy - 150))
                    .add("iMax", "" + (energy + 150))
                    .build();
            Request request = new Request.Builder()
                    .url(ConstantsUtil.GET_MEAL_SETS)
                    .post(requestBody)
                    .build();

            List<Meal> meals = new ArrayList<>();
            try {
                Response response = okHttpClient.newCall(request).execute();
                if (response == null) {
                    return null;
                }
                String respStr = response.body().string();
                parseItems(meals, respStr);
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return null;
            } catch (JSONException e) {
                Log.e(TAG, "doInBackground: ", e);
                return null;
            }
            return meals;
        }

        @Override
        protected void onPostExecute(List<Meal> meals) {
            if (meals == null) {
                refreshLayout.finishRefresh(false);
                loadingView.findViewById(R.id.progressBar).setVisibility(View.GONE);
                TextView textView = loadingView.findViewById(R.id.loading);
                textView.setText("服务器异常。");
                return;
            }
            if (meals.size() == 0) {
                refreshLayout.finishRefresh(true);
                loadingView.findViewById(R.id.progressBar).setVisibility(View.GONE);
                TextView textView = loadingView.findViewById(R.id.loading);
                textView.setText("暂无该范围的套餐。");
                return;
            }
            refreshLayout.finishRefresh(true);
            loadingView.setVisibility(View.GONE);
            mAdapter.setMeals(meals);


            ScaleAnimation sa = new ScaleAnimation(1f, 1f, 1.1f, 1f,
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f);
            sa.setDuration(1000);

            AlphaAnimation aa = new AlphaAnimation(0, 1);
            aa.setDuration(1000);

            AnimationSet as = new AnimationSet(true);
            as.setDuration(1000);
            as.addAnimation(sa);
            as.addAnimation(aa);
            mRecyclerView.startAnimation(as);
        }
    }

    private void parseItems(List<Meal> meals, String respStr) throws JSONException {
        JSONArray jsonArray = new JSONArray(respStr);
        for (int i = 0; i < jsonArray.length(); i ++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Meal meal = new Meal();
            meal.setId(jsonObject.getInt("ID"));
            meal.setEnergy(jsonObject.getInt("Energy"));
            meal.setElements(jsonObject.getString("Elements"));
            meal.setRecipes(jsonObject.getString("Recipes"));
            meal.setMealName(jsonObject.getString("SetName"));
            meal.setAdder(jsonObject.getString("Adder"));
            meal.setProtein(jsonObject.getInt("Protein"));
            meal.setFat(jsonObject.getInt("Fat"));
            meal.setCarbohydrate(jsonObject.getInt("Carbohydrate"));
            meals.add(meal);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (asyncTask != null) {
            // 销毁时要取消，Remember it.
            asyncTask.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
